﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Abp.Application.Services;
using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.AutoMapper;
using Abp.Domain.Repositories;
using XHD.WXZJ.Authorization.Roles;
using XHD.WXZJ.Roles.Dto;
using XHD.WXZJ.Users;

namespace XHD.WXZJ.Roles
{
    /* THIS IS JUST A SAMPLE. */
    public class RoleAppService : WXZJAppServiceBase,IRoleAppService
    {
        private readonly RoleManager _roleManager;
        private readonly IPermissionManager _permissionManager;
        private readonly IRepository<Role> _roleReposity;
        private readonly IRepository<User,long> _userRepository;
        public RoleAppService(RoleManager roleManager, 
          IPermissionManager permissionManager,
          IRepository<Role> roleReposity,
          IRepository<User, long> userRepository)
        {
            _roleManager = roleManager;
            _permissionManager = permissionManager;
            _roleReposity = roleReposity;
            _userRepository = userRepository;
        }

        public async Task UpdateRolePermissions(UpdateRolePermissionsInput input)
        {
            var role = await _roleManager.GetRoleByIdAsync(input.RoleId);
            var grantedPermissions = _permissionManager
                .GetAllPermissions()
                .Where(p => input.GrantedPermissionNames.Contains(p.Name))
                .ToList();

            await _roleManager.SetGrantedPermissionsAsync(role, grantedPermissions);
        }

        public async Task UpdateRole(RoleInput input)
        {
            var role = await _roleManager.GetRoleByIdAsync(input.RoleId);
            role.DisplayName = input.DisplayName;
        
            var result = await _roleManager.UpdateAsync(role);
        }

        /// <summary>
        /// 获取所有角色
        /// </summary>
        /// <returns></returns>
        public ListResultOutput<RoleDto> GetAllRoles()
        {
            var roles = _roleManager.Roles.Where(role => role.IsDeleted == false).ToList();
            var roleDtos = roles.MapTo<List<RoleDto>>();
            foreach (var role in roleDtos)
            {
                var user = _userRepository.GetAllList(u => u.Id == role.CreatorUserId).FirstOrDefault();
                role.CreatorUserName = user!=null? user.UserName:string.Empty;
                user = _userRepository.GetAllList(u => u.Id == role.LastModifierUserId).FirstOrDefault();
                role.LastModifierUserName = user != null ? user.UserName : string.Empty;
            }
            var result = new ListResultOutput<RoleDto>
            {
                Items = roleDtos
               
            };
            return result;
        }
        /// <summary>
        /// 分页获取所有角色
        /// </summary>
        /// <returns></returns>
        public PagedResultOutput<RoleDto> GetAllRolesByPage()
        {
            var roles = _roleManager.Roles.Where(role => role.IsDeleted == false).ToList();
            var roleDtos = roles.MapTo<List<RoleDto>>();
            foreach (var role in roleDtos)
            {
                var user = _userRepository.GetAllList(u => u.Id == role.CreatorUserId).FirstOrDefault();
                role.CreatorUserName = user.UserName;
                user = _userRepository.GetAllList(u => u.Id == role.LastModifierUserId).FirstOrDefault();
                role.LastModifierUserName = user.UserName;
            }
            var result = new PagedResultOutput<RoleDto>
            {
                Items = roleDtos,
                TotalCount = roles.Count
                 
            };
            return result;
        }
        public async Task DeleteRoleByRoleId(RoleInput input)
        {

            var role = await _roleManager.FindByNameAsync(input.RoleName);
             
            if (role != null)
            {
                await _roleManager.DeleteAsync( role);
            }
                
        }

        public async Task CreateRole(RoleInput input)
        {

            var role = new Role(AbpSession.TenantId, input.RoleName, input.DisplayName);
            await _roleManager.CreateAsync(role);
        }

        public RoleDto GetRoleByRoleId(int roleId)
        {
            var role = _roleReposity.GetAll().FirstOrDefault(r => r.Id == roleId); //_roleManager.GetRoleByIdAsync(roleId);
            return role.MapTo<RoleDto>();
        }
    }
}